#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from models import db, Problem
import json

def init_problems():
    """初始化题库"""
    app = create_app()
    
    with app.app_context():
        # 检查是否已有题目，如果有则跳过
        existing_count = Problem.query.count()
        if existing_count > 0:
            print(f"题库中已有 {existing_count} 道题目，跳过初始化")
            return
        
        # 定义题目数据
        problems_data = [
            {
                "title": "Hello World",
                "description": "编写一个程序，输出 'Hello, World!'",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "",
                        "output": "Hello, World!"
                    }
                ]),
                "difficulty": "easy",
                "category": "基础编程"
            },
            {
                "title": "两数之和",
                "description": """给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。

示例：
输入：nums = [2,7,11,15], target = 9
输出：[0,1]
解释：因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。

输入：nums = [3,2,4], target = 6
输出：[1,2]

输入：nums = [3,3], target = 6
输出：[0,1]""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "[2,7,11,15]\n9",
                        "output": "[0,1]"
                    },
                    {
                        "input": "[3,2,4]\n6",
                        "output": "[1,2]"
                    },
                    {
                        "input": "[3,3]\n6",
                        "output": "[0,1]"
                    }
                ]),
                "difficulty": "medium",
                "category": "数组"
            },
            {
                "title": "反转字符串",
                "description": """编写一个函数，其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间，你必须原地修改输入数组、使用 O(1) 的额外空间来解决这一问题。

示例：
输入：["h","e","l","l","o"]
输出：["o","l","l","e","h"]

输入：["H","a","n","n","a","h"]
输出：["h","a","n","n","a","H"]""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "['h','e','l','l','o']",
                        "output": "['o','l','l','e','h']"
                    },
                    {
                        "input": "['H','a','n','n','a','h']",
                        "output": "['h','a','n','n','a','H']"
                    }
                ]),
                "difficulty": "easy",
                "category": "字符串"
            },
            {
                "title": "斐波那契数列",
                "description": """斐波那契数列是一个数列，其中每个数都是前两个数的和。数列的前几个数是：0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

编写一个函数，计算斐波那契数列的第n项。

示例：
输入：n = 4
输出：3
解释：F(4) = F(3) + F(2) = 2 + 1 = 3

输入：n = 6
输出：8
解释：F(6) = F(5) + F(4) = 5 + 3 = 8""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "4",
                        "output": "3"
                    },
                    {
                        "input": "6",
                        "output": "8"
                    },
                    {
                        "input": "10",
                        "output": "55"
                    }
                ]),
                "difficulty": "easy",
                "category": "动态规划"
            },
            {
                "title": "最大子数组和",
                "description": """给你一个整数数组 nums ，请你找出一个具有最大和的连续子数组（子数组最少包含一个元素），返回其最大和。

子数组 是数组中的一个连续部分。

示例：
输入：nums = [-2,1,-3,4,-1,2,1,-5,4]
输出：6
解释：连续子数组 [4,-1,2,1] 的和最大，为 6 。

输入：nums = [1]
输出：1

输入：nums = [5,4,-1,7,8]
输出：23""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "[-2,1,-3,4,-1,2,1,-5,4]",
                        "output": "6"
                    },
                    {
                        "input": "[1]",
                        "output": "1"
                    },
                    {
                        "input": "[5,4,-1,7,8]",
                        "output": "23"
                    }
                ]),
                "difficulty": "medium",
                "category": "动态规划"
            },
            {
                "title": "Python数据类型",
                "description": "以下哪个是Python的内置数据类型？",
                "type": "choice",
                "answer": "list",
                "test_cases": json.dumps([
                    {
                        "options": ["list", "array", "vector", "sequence"],
                        "correct": "list"
                    }
                ]),
                "difficulty": "easy",
                "category": "Python基础"
            },
            {
                "title": "Python列表操作",
                "description": "在Python中，如何向列表末尾添加一个元素？",
                "type": "choice",
                "answer": "append()",
                "test_cases": json.dumps([
                    {
                        "options": ["add()", "append()", "insert()", "push()"],
                        "correct": "append()"
                    }
                ]),
                "difficulty": "easy",
                "category": "Python基础"
            },
            {
                "title": "Python字典",
                "description": "Python字典的键必须是不可变类型，以下哪个可以作为字典的键？",
                "type": "choice",
                "answer": "tuple",
                "test_cases": json.dumps([
                    {
                        "options": ["list", "dict", "tuple", "set"],
                        "correct": "tuple"
                    }
                ]),
                "difficulty": "medium",
                "category": "Python基础"
            },
            {
                "title": "冒泡排序",
                "description": """实现冒泡排序算法。冒泡排序是一种简单的排序算法，它重复地遍历要排序的数列，一次比较两个元素，如果它们的顺序错误就把它们交换过来。

示例：
输入：[64, 34, 25, 12, 22, 11, 90]
输出：[11, 12, 22, 25, 34, 64, 90]

输入：[5, 2, 4, 6, 1, 3]
输出：[1, 2, 3, 4, 5, 6]""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "[64, 34, 25, 12, 22, 11, 90]",
                        "output": "[11, 12, 22, 25, 34, 64, 90]"
                    },
                    {
                        "input": "[5, 2, 4, 6, 1, 3]",
                        "output": "[1, 2, 3, 4, 5, 6]"
                    }
                ]),
                "difficulty": "medium",
                "category": "排序算法"
            },
            {
                "title": "二分查找",
                "description": """实现二分查找算法。二分查找是一种在有序数组中查找特定元素的搜索算法。

给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回 -1。

示例：
输入：nums = [-1,0,3,5,9,12], target = 9
输出：4
解释：9 出现在 nums 中并且下标为 4

输入：nums = [-1,0,3,5,9,12], target = 2
输出：-1
解释：2 不存在 nums 中因此返回 -1""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "[-1,0,3,5,9,12]\n9",
                        "output": "4"
                    },
                    {
                        "input": "[-1,0,3,5,9,12]\n2",
                        "output": "-1"
                    }
                ]),
                "difficulty": "medium",
                "category": "搜索算法"
            },
            {
                "title": "有效括号",
                "description": """给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串 s ，判断字符串是否有效。

有效字符串需满足：
1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。

示例：
输入：s = "()"
输出：true

输入：s = "()[]{}"
输出：true

输入：s = "(]"
输出：false

输入：s = "([)]"
输出：false""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": '"()"',
                        "output": "True"
                    },
                    {
                        "input": '"()[]{}"',
                        "output": "True"
                    },
                    {
                        "input": '"(]"',
                        "output": "False"
                    },
                    {
                        "input": '"([)]"',
                        "output": "False"
                    }
                ]),
                "difficulty": "easy",
                "category": "栈"
            },
            {
                "title": "爬楼梯",
                "description": """假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢？

示例：
输入：n = 2
输出：2
解释：有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶

输入：n = 3
输出：3
解释：有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "2",
                        "output": "2"
                    },
                    {
                        "input": "3",
                        "output": "3"
                    },
                    {
                        "input": "4",
                        "output": "5"
                    }
                ]),
                "difficulty": "easy",
                "category": "动态规划"
            },
            {
                "title": "Python异常处理",
                "description": "在Python中，用于处理异常的语句块是？",
                "type": "choice",
                "answer": "try-except",
                "test_cases": json.dumps([
                    {
                        "options": ["if-else", "try-except", "for-while", "def-return"],
                        "correct": "try-except"
                    }
                ]),
                "difficulty": "easy",
                "category": "Python基础"
            },
            {
                "title": "Python文件操作",
                "description": "在Python中，打开文件时使用什么模式可以同时读取和写入？",
                "type": "choice",
                "answer": "r+",
                "test_cases": json.dumps([
                    {
                        "options": ["r", "w", "r+", "a"],
                        "correct": "r+"
                    }
                ]),
                "difficulty": "medium",
                "category": "Python基础"
            },
            {
                "title": "Python装饰器",
                "description": "Python装饰器使用什么符号？",
                "type": "choice",
                "answer": "@",
                "test_cases": json.dumps([
                    {
                        "options": ["#", "@", "$", "%"],
                        "correct": "@"
                    }
                ]),
                "difficulty": "medium",
                "category": "Python高级"
            }
        ]
        
        # 创建题目
        for problem_data in problems_data:
            problem = Problem(**problem_data)
            db.session.add(problem)
        
        # 提交到数据库
        db.session.commit()
        
        print(f"成功创建 {len(problems_data)} 道题目")
        print("题目列表：")
        for problem in Problem.query.all():
            print(f"- {problem.title} ({problem.type}, {problem.difficulty})")

if __name__ == '__main__':
    init_problems()
